<template>
  <div class="warp" id="app_box">
    <router-view v-slot="{ Component }">
      <keep-alive>
        <component v-if="route.meta.keepAlive" :key="route.name" :is="Component"></component>
      </keep-alive>
      <component v-if="!route.meta.keepAlive" :key="route.name" :is="Component"></component>
    </router-view>
    <van-back-top target=".warp" immediate bottom="100" :offset="400" />
  </div>
  <!-- 签名弹窗 -->
  <van-popup :close-on-click-overlay="false" v-model:show="showSinger" round :style="{ padding: '20px 34px' }">
    <div class="singer_value">{{ t('pleaseSignFirst') }}</div>
    <div class="btn_two">
      <van-button @click="cancelSinger"> {{ t('cancel') }}</van-button>
      <van-button type="primary" :loading="loading" @click="getSinger">
        {{ t('sign') }}</van-button>
    </div>
  </van-popup>
</template>
<script setup>
import { ethers } from "ethers";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
import {jsonAbiToHumanReadable} from "../utils/index"
const route = useRoute()
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import { useI18n } from "vue-i18n";
import { showToast } from "vant";
import { useStore } from "vuex";
import eth from "../utils/eth";
import bus from "@/utils/bus.js"
import { switchNetwork } from "@/utils/eth.js";
import bankEth from "@/utils/bankEth"
const store = useStore();
const loading = ref(false);
const showSinger = ref(false);
const active = ref(0);
const showLoading = ref(false)
const { locale, t } = useI18n();
// 使用计算属性实现响应式
const goToPage = (value) => {
  router.push({
    name: value,
  });
};
eth.linkWallet()
const fn = () => {
  if (typeof window.ethereum !== 'undefined' || (typeof window.web3 !== 'undefined')) {
    // 用户正在使用 Web3 浏览器或连接了以太坊网络
  } else {
    // 用户没有连接 Web3 浏览器或以太坊网络
    showToast(t('pleaseInWeb3'))
  }
  ethereum.on("accountsChanged", async function (accounts) {
    if(accounts&&accounts[0]){
      if(store.state.address!=accounts[0].toLowerCase()){
        store.commit('changeAddress', accounts[0].toLowerCase())
        eth.linkWallet()
        initData()
        localStorage.removeItem("accountSinger");
        ifHasSinger();
        bus.emit("init")
        if (router.currentRoute.value.meta && router.currentRoute.value.meta.returnIndex) {
          router.push({ name: 'index' })
        }
      }
    }
 
  });
  window.ethereum.on("chainChanged", async(chain) => {
    await switchNetwork(chain);
    eth.linkWallet()
  });


};
const initData = async ()=> {
  bankEth.getParent()
  bankEth.getPrice()
  bankEth.getUserInfo()
  bankEth.getSystem()
  // 获取我创建的锁
  bankEth.normalLocksForUser()
}

initData()


const cancelSinger = () => {
  showSinger.value = false;
  loading.value = false
  goToPage("index");
};
const getSinger = async () => {
  loading.value = true;
  try {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const accounts = await provider.send("eth_requestAccounts", []);
    const signer = provider.getSigner();
    let msgHash = ethers.utils.solidityKeccak256(["address"], [accounts[0]]);
    console.log("msgHash:", msgHash);
    let timeOut = setTimeout(()=>{
        cancelSinger()
        showToast(t('signFail'));
    },1000*60*1)
    const sig = await signer.signMessage(ethers.utils.arrayify(msgHash));
    clearTimeout(timeOut)
    loading.value = false;
    showSinger.value = false;
    localStorage.setItem("accountSinger", accounts[0].toLowerCase());
    showToast(t('signSuccess'));
  } catch (error) {
    showToast(t('signFail'));
    loading.value = false;
  }
};
const ifHasSinger = async () => {
  if (
    [
      "pandora",
      "group",
      "user",
    ].includes(router.currentRoute.value.name)
  ) {
    if (localStorage.getItem("accountSinger")) {

      if(localStorage.getItem("accountSinger")!=store.state.address){
        showSinger.value = true
      }
      // 有签名
    } else {
      showSinger.value = true;
    }
  }
};
ifHasSinger();
watch(
  () => router.currentRoute.value,
  (newValue) => {
    console.log("newValue", newValue);
    ifHasSinger();
  },
  { immediate: true }
);

onUnmounted(() => {
})
onMounted(() => {
  fn();
});
</script>
<style lang="scss" scoped>

.singer_value {
  text-align: center;
  color: var(--van-text-color);
  margin: 20px;
  font-size: 12px;
}

.btn_two {
  display: flex;
  width: 200px;
  justify-content: space-between;

  .van-button {
    height: 32px;
    border-radius: 20px;
    width: 48%;
  }
}

.tabimg {
  display: block;
  height: 16px;
  width: 24px;
  margin-right: 6px;
}

.warp {
  font-size: 0.32rem;
  box-sizing: border-box;
  height: 100%;
  overflow: auto;
  // scroll-behavior: smooth;
  // display: flex;
  // flex-direction: column;
  padding-bottom: 2rem;
}
.miningIcon{
  font-size: 14px;
}
.hui {
  fill: #c4c4c6;
  color: #c4c4c6;
}
</style>
